package com.humi.partner.front.service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.esotericsoftware.minlog.Log;
import com.humi.cloud.common.exception.HumiRuntimeException;
import com.humi.cloud.common.model.ResponseCode;
import com.humi.cloud.common.model.Result;
import com.humi.cloud.common.utils.BeanUtil;
import com.humi.cloud.common.utils.JsonUtil;
import com.humi.cloud.concurrent.store.LockCacheStore;
import com.humi.cloud.security.support.utils.SecurityUtil;
import com.humi.cloud.share.user.dict.AuthStatus;
import com.humi.partner.common.entity.PartnerApplyRecord;
import com.humi.partner.common.entity.PartnerBase;
import com.humi.partner.common.entity.PartnerType;
import com.humi.partner.common.feign.UserCenterAuthBack;
import com.humi.partner.common.service.PartnerApplyRecordService;
import com.humi.partner.common.service.PartnerBaseService;
import com.humi.partner.common.service.PartnerTypeService;
import com.humi.partner.front.model.PartnerBasePO;
import com.humi.partner.front.model.auth.AuthUserCompanyDetails;
import com.humi.partner.manager.dao.ManagerPartnerBaseMapper;

/**
 * 
 * <pre>
 * <b>Description:</b> 
 * <b>Author:</b> TianJunmin
 * <b>Date:</b> 2019年10月11日
 * </pre>
 */
@Service
public class FrontPartnerBaseService {

	@Autowired
	LockCacheStore lockCacheStore;

	@Autowired
	PartnerBaseService partnerBaseService;

	@Autowired
	PartnerTypeService partnerTypeService;

	@Autowired
	PartnerApplyRecordService partnerApplyRecordService;

	@Autowired
	ManagerPartnerBaseMapper baseMapper;

	@Autowired
	UserCenterAuthBack userCenterAuthBack;

	private void checkUserAuthStatus() {
		try {
			String userId=SecurityUtil.getUser().getSourceId();
			Result result = userCenterAuthBack.getEnterPriseVerificationDetailsByUserId(userId);
			if (result != null && result.isSuccess()) {
				AuthUserCompanyDetails auth = JsonUtil.toBean(JsonUtil.toJson(result.getData()),
						AuthUserCompanyDetails.class);
				if(auth==null||auth.getCurrInfo()==null) {
					throw HumiRuntimeException.newInstance(ResponseCode.FAILED,"请先进行企业认证后再申请加入");
				}
				if(auth.getCurrInfo().getStatus()!=AuthStatus.SUCCESS.getCode()) {
					throw HumiRuntimeException.newInstance(ResponseCode.FAILED,"请检查企业认证状态");
				}
			}

		} catch (Exception e) {
			Log.error(e.getMessage());
		}
	}

	/**
	 * 
	 * <pre>
	 * 修改使用次数
	 * </pre>
	 * 
	 * @param typeId
	 * @param type   1.增加；2.减少
	 */
	public void modifyUseCount(String typeId, int type) {
		PartnerType old = partnerTypeService.getById(typeId);
		if (old == null) {
			throw HumiRuntimeException.newInstance(ResponseCode.FAILED, "伙伴类型不存在");
		}
		if (type == 1) {
			old.setUseCount(old.getUseCount() + 1);
		} else {
			old.setUseCount(old.getUseCount() - 1);
			if (old.getUseCount() < 0) {
				old.setUseCount(0);
			}
		}
		boolean ret = partnerTypeService.updateById(old);
		if (!ret) {
			throw HumiRuntimeException.newInstance(ResponseCode.FAILED, "保存数据失败[1]");
		}
	}

	/**
	 * 
	 * <pre>
	 * 保存或修改申请记录
	 * </pre>
	 * 
	 * @param partner
	 * @return
	 */
	@Transactional
	public Result applyPartner(PartnerBasePO partner) {
		if (StringUtils.isEmpty(partner.getUserPhone()) || StringUtils.isEmpty(partner.getContacts())
				|| StringUtils.isEmpty(partner.getApplyType()) || StringUtils.isEmpty(partner.getLegalPerson())) {
			return Result.fail("参数错误");
		}
		partner.clearDefaultValue();
		String userId = SecurityUtil.getUser().getSourceId();
		String key = "com:humi:partner:front:FrontPartnerBaseService:applyPartner:".concat(userId);
		try {
			boolean locked = lockCacheStore.lock(key, 1, TimeUnit.MINUTES);
			if (!locked) {
				throw HumiRuntimeException.newInstance(ResponseCode.FAILED, "请稍后再试！");
			}
			checkUserAuthStatus();
			QueryWrapper<PartnerBase> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(PartnerBase::getUserId, userId);
			PartnerBase old = partnerBaseService.getOne(queryWrapper);
			partner.setUserId(userId);
			partner.setUserAccount(SecurityUtil.getUser().getAccount());
			PartnerBase newApply = new PartnerBase();

			BeanUtil.copyNotEmptyProperties(partner, newApply);
			if (old != null) {
				// 修改或返回错误信息
				if (old.getApplyStatus() != 2) {// 审核通过的
					return new Result(ResponseCode.FAILED, "不需要提交信息", old);
				} else {
					// 如果是驳回但可重新提交，修改状态未未审核
					if (old.getApplyStatus() == 2) {
						newApply.setApplyStatus(0);
					}
					newApply.setId(old.getId());
					boolean ret = partnerBaseService.updateById(newApply);
					if (ret) {
						// 如果是驳回但可重新提交记录提交记录
						if (old.getApplyStatus() == 2) {
							PartnerApplyRecord record = new PartnerApplyRecord();
							record.setPartnerId(old.getId());
							record.setApplyReason("重新提交资料");
							record.setApplyStatus(old.getApplyStatus());
							record.setApplyTime(new Date());
							partnerApplyRecordService.save(record);
						}
						// 如果旧的类型和新的不一样
						if (old.getApplyType() != partner.getApplyType()) {
							modifyUseCount(old.getApplyType(), 2);
						}
						modifyUseCount(newApply.getApplyType(), 1);
					} else {
						return Result.fail("保存数据失败[2]");
					}
				}
			} else {
				newApply.setApplyStatus(0);
				boolean ret = partnerBaseService.save(newApply);
				if (ret) {
					modifyUseCount(newApply.getApplyType(), 1);
				} else {
					return Result.fail("保存数据失败[2]");
				}
			}
			return Result.ok();
		} finally {
			lockCacheStore.unlock(key);
		}
	}

	public Result getApplyPartner() {
		String userId = SecurityUtil.getUser().getSourceId();
		QueryWrapper<PartnerBase> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(PartnerBase::getUserId, userId);
		PartnerBase old = partnerBaseService.getOne(queryWrapper);
		if (old != null) {
			PartnerBasePO po = baseMapper.getOne(old.getId());
			if (po != null) {
				return Result.ok(po);
			}
		}
		return Result.fail("未找到记录");
	}

	public Result saveApplyRecord(PartnerApplyRecord record) {
		boolean ret = partnerApplyRecordService.save(record);
		return Result.ok(ret);
	}

	public Result getApplyRecord() {
		List<PartnerApplyRecord> list = partnerApplyRecordService.list();
		return Result.ok(list);
	}
}
